<template>
  <!-- 模态框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="dialogTitle"
    draggable
    destroy-on-close
    width="600px"
    @close="close"
  >
    <el-form
      ref="ruleFormRef"
      :model="form"
      :rules="rules"
      status-icon
      label-width="140px"
    >
      <el-form-item label="商品名称" prop="skuName">
        <el-input
          v-model="form.skuName"
          autocomplete="off"
          placeholder="请输入商品名称"
        />
      </el-form-item>

      <el-form-item label="商品分类" prop="skuCategory">
        <!-- <el-select-v2
          v-model="form.skuCategory"
          :options="category"
          placeholder="请选择分类"
          style="width: 300px"
        /> -->
        <el-select v-model="form.skuCategory" placeholder="请选择商品分类">
          <el-option
            v-for="item in category"
            :key="item.id"
            :label="item.skuCategoryName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品属性" prop="skuAttrs">
        <el-input
          v-model="form.skuAttrs"
          autocomplete="off"
          placeholder="请输入商品属性"
        />
      </el-form-item>
      <el-form-item label="商品图片" prop="skuImgList">
        <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          action="#"
          :http-request="uploadFile"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          list-type="picture"
          multiple
        >
          <el-button type="primary">上传图片</el-button>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png files with a size less than 500kb
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="商品价格" prop="skuPrice">
        <el-input
          v-model="form.skuPrice"
          autocomplete="off"
          placeholder="请输入商品价格"
        />
      </el-form-item>

      <el-form-item label="商品原价" prop="skuOldPrice">
        <el-input
          v-model="form.skuOldPrice"
          autocomplete="off"
          placeholder="请输入商品原价"
          type="number"
        />
      </el-form-item>

      <el-form-item label="商品库存" prop="skuStocks">
        <el-input
          v-model="form.skuStocks"
          autocomplete="off"
          placeholder="请输入商品库存"
        />
      </el-form-item>
      <el-form-item label=" 商品状态" prop="skuStatus">
        <el-radio-group v-model="form.skuStatus">
          <el-radio :label="2" size="large">稍后上架</el-radio>
          <el-radio
            :label="1"
            size="large"
            :disabled="!form.id"
            title="不可以直接上架"
            >直接上架</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item label="商品详情" prop="skuDesc">
        <el-input
          v-model="form.skuDesc"
          type="textarea"
          autocomplete="off"
          style="width: 300px"
          placeholder="请输入商品详情信息"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button
          type="primary"
          :loading="isLoading"
          @click="submitForm(ruleFormRef)"
          >确认</el-button
        >

        <el-button @click="cancel">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
// 商品表单
// 添加、修改 商品窗口
import { ref, reactive, defineProps, computed } from "vue";
import { ElMessage } from "element-plus";
// 引入store
import { useStore } from "vuex";
import type { UploadProps, UploadUserFile } from "element-plus";

const store = useStore();
// 获取父组件传入的值
const props = defineProps([]); //props参数
const emit = defineEmits(["getData"]); //emit事件
var dialogFormVisible = ref(false);
var isLoading = ref(false);
var dialogTitle = ref(""); // 弹出框标题
// 商品分类(需要请求数据)
let category = ref([]);
// 存放数据
const ruleFormRef = ref();
const fileList = ref<UploadUserFile[]>([]);

// 获取分类信息
const getData = () => {
  store.dispatch("category/getCategory");
  category = computed(() => store.getters["category/categoryList"]);
};
getData();
// 表单数据
let form = reactive({
  id: undefined,
  skuName: "",
  skuCategory: "", //分类
  skuAttrs: "", //属性
  skuImgList: "", //图片
  skuStatus: 2, //状态(默认为2未上架)
  skuPrice: "", //价格
  skuOldPrice: "", //原价
  skuStocks: "", //库存
  skuDesc: "" //详情
});

// 验证规则
const rules = reactive({
  skuName: [
    {
      required: true,
      message: "商品名称不能为空",
      trigger: "blur"
    },
    {
      min: 1,
      max: 50,
      message: "Length should be 1 to 50",
      trigger: "blur"
    }
  ],
  skuCategory: [
    {
      // type: "array",
      required: true,
      message: "商品类别不能为空",
      trigger: "blur"
    }
  ],
  skuAttrs: [
    {
      required: true,
      message: "商品属性不能为空",
      trigger: "blur"
    }
  ],
  skuImgList: [
    {
      // type: "array",
      required: false,
      message: "商品图片不能为空",
      trigger: "blur"
    }
  ],
  skuPrice: [
    {
      required: true,
      message: "商品价格不能为空",
      trigger: "blur"
    },
    {
      pattern: /^[0-9]*$/,
      required: true,
      message: "商品价格不能为非数字",
      trigger: "blur"
    },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "商品价格不能以 0 开头",
      trigger: "blur"
    }
  ],
  skuStocks: [
    {
      required: true,
      message: "商品库存不能为空",
      trigger: "blur"
    }
  ],

  skuDesc: [
    {
      required: true,
      message: "商品详情不能为空",
      trigger: "blur"
    }
  ]
});
// 重置表单
const reset = () => {
  console.log("reset");
  form.id = undefined;
  form.skuName = "";
  form.skuCategory = [];
  form.skuAttrs = "";
  form.skuImgList = {};
  form.skuStatus = 2;
  form.skuPrice = "";
  form.skuOldPrice = "";
  form.skuStocks = "";
  form.skuDesc = "";
  fileList.value = [];
};
// 开启弹窗
const openDialog = (title: any = "新增商品", data: any = {}) => {
  reset(); //重置表单
  dialogTitle = title;
  form = reactive({ ...form, ...data });
  // 开启
  dialogFormVisible.value = true;
};

// 表单确认回调
const submitForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async (valid: any, fields: any) => {
    if (!fileList.value.length)
      return ElMessage({
        message: "请上传图片",
        type: "error",
        showClose: true
      });
    if (valid) {
      let files = fileList.value;
      const formData = new FormData();
      for (let key in form) {
        if (key == "skuImgList") {
          files.map((e: any) => {
            formData.append("images", e.raw);
          });
        } else if (key == "id") {
          // 如果等于id 并且id为真
          if (form[key]) {
            formData.append(key, form[key]);
          }
        } else {
          formData.append(key, form[key]);
        }
      }

      isLoading.value = true;
      if (form.id) {
        // 修改
        try {
          let res = await store.dispatch("goods/editGoods", formData);
          if (res) {
            isLoading.value = false;
            dialogFormVisible.value = false;
            emit("getData");
            ElMessage({
              message: "修改成功",
              type: "success",
              showClose: true
            });
          }
        } catch (error: any) {
          isLoading.value = false;
          ElMessage({
            message: error,
            type: "error",
            showClose: true
          });
        }
      } else {
        // 添加
        // 获取到表单发请求 请求成功后关闭窗口
        try {
          let res = await store.dispatch("goods/addGoods", formData);
          if (res) {
            isLoading.value = false;
            dialogFormVisible.value = false;
            emit("getData");
            ElMessage({
              message: "添加成功",
              type: "success",
              showClose: true
            });
          }
        } catch (error: any) {
          isLoading.value = false;
          ElMessage({
            message: error,
            type: "error",
            showClose: true
          });
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 取消
const cancel = () => {
  dialogFormVisible.value = false;
};
// 关闭时触发回调
const close = () => {
  reset();
};

// 上传图片 存储图片，删除图片 种新存储图片
// 存储图片

// 删除回调
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {};
// 点击文件列表中已上传的文件时的钩子
const handlePreview: UploadProps["onPreview"] = (file) => {};
//上传
const uploadFile = () => {};

// 暴露方法
defineExpose({
  openDialog
});
</script>

<style>
.el-input {
  width: 300px;
}
</style>
